var https = require('https');
var qs = require('querystring');
var request = require('request');

// 个人私有
var userAppid = "";
var userSecret = "";
var productId = "";

var macAddr = "C60504030006";

var url = "api.weixin.qq.com";
var token = "/cgi-bin/token?";
var device = '/device/authorize_device?';
var qrcode = '/device/getqrcode?';
var createMenu = '/cgi-bin/menu/create?';
var getMenu = '/cgi-bin/menu/get?';
var curToken = "";
var deviceId = "";

var access_token = {
    grant_type: "client_credential",
    appid: userAppid,
    secret: userSecret
};

var device_authorize = {
    access_token: curToken
};

var device_qrcode = {
    access_token: curToken,
    product_id: productId
}

var tokenUrl = token + qs.stringify(access_token);
console.log(tokenUrl);


var wechatGETData = function(path, key, callback) {
	var options = {
		hostname: url,
		path: path,
		method: 'GET'
	};

	var req = https.request(options, function(res) {
		console.log('STATUS: ' + res.statusCode);
		console.log('HEADERS: ' + JSON.stringify(res.headers));
		res.setEncoding('utf8');
		res.on('data', function (chunk) {
			console.log('BODY: ' + chunk);
			var buf = JSON.parse(chunk);
			var retData = buf[key];
			callback(retData);
		});
	});

	req.on('error', function(e) {
		console.log('problem with requset:' + e.message);
	});

	req.end();
}

var wechatPOSTData = function(path, postData, headers, callback) {
	var options = {
		hostname: url,
		path: path,
		method: 'POST',
		headers: headers
	};

	var req = https.request(options, function(res) {
		console.log('STATUS: ' + res.statusCode);
		console.log('HEADERS: ' + JSON.stringify(res.headers));
		res.setEncoding('utf8');
		res.on('data', function (chunk) {
			console.log('BODY: ' + chunk);
		});
	});

	req.on('error', function(e) {
		console.log('problem with requset:' + e.message);
	});

	console.log(postData);
	req.write(postData);

	req.end();
}

var deviceAuthorizeData = {
    device_num: "1",
    device_list: [
        {
            "id": deviceId,  // 上面申请的device_id
            "mac": macAddr,     // 需要绑定的蓝牙的实际MAC地址（注意：没有冒号）
            "connect_protocol": "3",   // 设置设备为BLE连接
            "auth_key": "",            // 加密秘钥，可以不填，（根据实际BLE设备的参数而定）
            "close_strategy": "1",
            "conn_strategy": "1", 
            "crypt_method": "0",       // 是否采用加密
            "auth_ver": "0",           // 加密版本
            "manu_mac_pos": "-1", 
            "ser_mac_pos": "-2", 
            "ble_simple_protocol": "0"
        }
    ], 
    "op_type": "1", 
    "product_id": productId
};

var menuData = {
    "button" : [
    {
        "name": "行业方案",
        "sub_button": [
        {
            "type": "click",
            "name": "血压计",
            "key": "V1002_BLOOD_PRESSURE"
        },
        {
            "type": "click",
            "name": "体温计",
            "key": "V1002_THERMOMTER"
        },
        {
            "type": "click",
            "name": "手环",
            "key": "V1002_WRISTBAND"
        },
        {
            "type": "click",
            "name": "蓝牙灯",
            "key": "V1002_LIGHT"
        },
        {
            "type": "click",
            "name": "其它产品",
            "key": "V1002_OTHER"
        }
        ]
    },
    {
        "name": "相关资料",
        "sub_button": [
        {
            "type": "view",
            "name": "模块手册",
            "url": "http://www.sulongcom.com/dgweb-96165.html"
        },
        {
            "type": "click",
            "name": "相关APP",
            "key": "V1003_APPLICATION_APK"
        }
        ]
    },
    {
        "name":"速龙",
        "sub_button":[
        {	
            "type":"view",
            "name":"速龙官网",
            "url":"http://www.sulongcom.com/",
        },
        {
            "type":"view",
            "name":"联系我们",
            "url":"http://www.sulongcom.com/contact.html",
        }]
    }]
};

var accessDeviceIdCallback = function(token) {
	console.log(token);
	curToken = token;
    device_authorize.access_token = curToken;
    device_qrcode.access_token = curToken;
    var qrcodeUrl = qrcode + qs.stringify(device_qrcode); 
    console.log(qrcodeUrl);
	// wechatGETData(qrcodeUrl, "deviceid", deviceIdCallback);
    deviceIdCallback(deviceId);
}

var deviceIdCallback = function(deviceid) {
	console.log(deviceid);
    var deviceUrl = device + qs.stringify(device_authorize); 
    console.log(deviceUrl);
	deviceAuthorizeData.device_list[0].id = deviceid;

	var bodyString = JSON.stringify(deviceAuthorizeData);

	var headers = {
		'Content-Type': 'application/json',
		'Content-Length': bodyString.length
	};

	wechatPOSTData(deviceUrl, bodyString, headers, authorizeCallback);
}

var authorizeCallback = function() {
}

var tempNullCallBack = function() {
}

var accessGetMenuCallback = function(token) {
	console.log(token);
	curToken = token;
    device_authorize.access_token = curToken;
    var getMenuUrl = getMenu + qs.stringify(device_authorize); 
    console.log(getMenuUrl);
	wechatGETData(getMenuUrl, "menu", accessCreateMenuCallback);
}

var accessCreateMenuCallback = function() {
    var createMenuUrl = 'http://' + url + createMenu + qs.stringify(device_authorize); 
    console.log(createMenuUrl);

    /*
	var bodyString = JSON.stringify(menuData);

	var headers = {
		'Content-Type': 'application/json',
		'Content-Length': bodyString.length
	};

	wechatPOSTData(createMenuUrl, bodyString, headers, tempNullCallBack);
    */
    var options = {
        url: createMenuUrl,
        form: JSON.stringify(menuData),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };

    request.post(options, function (err, res, body) {
        if (err) {
            console.log(err)
        }else {
            console.log(body);
        }
    });
}


wechatGETData(tokenUrl, "access_token", accessGetMenuCallback);


